let wechatUserId;

$(function () {
    wechatUserId = $('#hiddenUserId').val();

    if (null === wechatUserId || wechatUserId === '') {
        wechatUserId = sessionStorage.getItem('loginWeChatUserId');
    } else {
        sessionStorage.setItem('loginWeChatUserId', wechatUserId);
    }

    // 特别分组默认隐藏
    sessionStorage.setItem('specialGroupStatus', '0');

    // 加载当前用户信息
    loadUserInfo();

    // 界面初始化时自动加载公司列表信息
    loadCompany();
});

function loadUserInfo() {
    showLoading();

    $.post(serverUrl + ':' + serverPort + serverName + '/user/info', {
        id: wechatUserId
    }, function (result) {
        hideLoading();

        let obj = JSON.parse(result);

        sessionStorage.setItem("loginUserId", obj.data.id);
        sessionStorage.setItem("loginUserAvatar", obj.data.avatar);
        sessionStorage.setItem("loginUserName", obj.data.name);
        sessionStorage.setItem("loginUserNickName", obj.data.nickName);
        sessionStorage.setItem("loginUserSex", obj.data.sex);
        sessionStorage.setItem("loginUserMobile", obj.data.mobile);
        sessionStorage.setItem("loginUserDescription", obj.data.description);

        if (obj.data.moduleList.length > 0) {
            let userModuleIdList = '@';

            $.each(obj.data.moduleList, function (i, item) {
                userModuleIdList += item.id + '@';
            });

            sessionStorage.setItem("userModuleIdList", userModuleIdList);
        } else {
            sessionStorage.setItem("userModuleIdList", '');
        }
    });
}

// 加载公司信息
function loadCompany() {
    $.post(serverUrl + ':' + serverPort + serverName + '/companyUser/iFindCompanyListByUserId', {
        userId: wechatUserId
    }, function (result) {
        let content = '';
        let obj = JSON.parse(result);
        let companyCount = 0;
        let tempCompanyId = 0;

        if (obj.code === 0) {
            $.each(obj.data, function (i, item) {
                content += '<div class="card" onclick="jumpToDevicePage(' + item.id + ',' + wechatUserId + ')">' + item.name + '</div>';
                tempCompanyId = item.id;
                companyCount++;
            });
        }

        $('#companyDiv').html(content);

        // 当公司有且只有一个时，自动跳转到二级界面
        if (companyCount === 1) jumpToDevicePage(tempCompanyId, wechatUserId);
    });
}

// 根据公司ID和用户ID跳转到详情界面
function jumpToDevicePage(companyId, userId) {
    sessionStorage.setItem('companyId', companyId);
    sessionStorage.setItem('userId', userId);

    window.location.href = 'wx/project/main';
}

// 保存数据到 sessionStorage
// sessionStorage.setItem("key", "value");

// 从 sessionStorage 获取数据
// let data = sessionStorage.getItem("key");

// 从 sessionStorage 删除保存的数据
// sessionStorage.removeItem("key");

// 从 sessionStorage 删除所有保存的数据
// sessionStorage.clear();